package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.*;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Employee;
import com.sky.entity.Setmeal;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.service.EmployeeService;
import com.sky.vo.DishVO;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜品业务层
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增菜品和对应口味数据
     */
    @Transactional//涉及到多表要加事务注解
    public void saveWithFlavors(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜品表添加1条数据
        dishMapper.saveWithFlavors(dish);
        //获取insert语句生成的主键值
        Long dishId = dish.getId();
        //向口味表添加数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() != 0){
            //向口味表插入n条数据
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.saveFlavors(flavors);
        }
    }

    /**
     * 菜品分页查询
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }
    /**
     * 批量删除菜品
     */
    @Transactional
    public void deleByIds(List<Long> ids) {
        //判断当前的商品是否能删除--是否处于起售中？
        List<Integer> status = dishMapper.getStatusByIds(ids);
        if(status.contains(StatusConstant.ENABLE)){
            //当前菜品属于起售中，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //判断当前的商品是否能删除--是否被套餐关联？
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size()!=0){
            //当前菜品被套餐关联，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //批量删除菜品数据
        dishMapper.deleByIds(ids);
        //批量删除口味数据
        dishFlavorMapper.deleByDishIds(ids);
    }

    /**
     * 根据id查询菜品和对应口味数据
     * @param id
     * @return
     */
    @Transactional
    public DishVO getById(Long id) {
        //根据菜品id查询菜品
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getBydishId(id);
        BeanUtils.copyProperties(dish,dishVO);
        if (dishFlavors!=null&&dishFlavors.size()!=0){
            dishVO.setFlavors(dishFlavors);
        }
        return dishVO;
    }

    /**
     * 修改菜品
     */
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品的基本信息
        dishMapper.updateDish(dish);
        //删除原有的口味数据
        dishFlavorMapper.deleByDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() != 0){
            //添加新的口味数据
            //这里一定要重新set dishId，因为新增的口味没有dishId的属性，不set就只能删除口味，不能添加(报sql错误)
            flavors.forEach(flavor -> {
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.saveFlavors(flavors);
        }
    }

    /**
     * 菜品起售、停售
     */
    @Transactional
    public void updateDishStatus(Integer status,Long id) {
        //创建菜品对象
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.updateDish(dish);
        //菜品停售后，对应的套餐也要停售
        if (status == StatusConstant.DISABLE){
            //根据菜品查询出对应的套餐id
            List<Long> setmealIds = setmealDishMapper.getSetmealIdByDishId(id);
            setmealIds.forEach(setmealId->{
                Setmeal setmeal = Setmeal.builder()
                        .id(setmealId)
                        .status(StatusConstant.DISABLE)
                        .build();
                setmealMapper.update(setmeal);
            });
        }
    }

    /**
     * 根据分类id查询菜品
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        //查询该分类下所有菜品
        List<Dish> dishList = dishMapper.getByCategoryId(categoryId);
        return dishList;
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Transactional
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getBydishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
